package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.config.login.Userparam;
import com.example.demo.datasource.multi.dao.*;
import com.example.demo.datasource.multi.entity.*;
import com.example.demo.entity.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Slf4j
@Controller
public class usercontroller {

    @Autowired
    com.example.demo.datasource.multi.entity.usertable usertable;
    @Autowired
    com.example.demo.datasource.multi.dao.usertablemapper usertablemapper;
    @Autowired
    com.example.demo.datasource.multi.dao.accountinfomapper accountinfomapper;
    @Autowired
    com.example.demo.datasource.multi.dao.usermapper usermapper;
    @Autowired
    selectstringmapper selectstringmapper;

    @ResponseBody
    @RequestMapping("/getuserlist")
    public JSON getuserlist(HttpServletRequest request,@RequestBody Map<String,String> params){
        System.out.println(params.get("realName"));
        System.out.println(params.get("username"));
        System.out.println(params.get("code"));

        String where = "";

        if (!(params.get("username") == null)){
            where = where + " and a.username like '%"+ params.get("username")+"%'";
        }
        if (!(params.get("realName") == null)){
            where = where + " and a.realName like '%"+ params.get("realName")+"%'";
        }
        if (!(params.get("code") == null) && !(params.get("code") =="")){
            String pcode = params.get("code");
            String gettypesql = "select type FROM organization WHERE `code` = '"+pcode+"'";

            String codetype = selectstringmapper.selectstring(gettypesql);

            where = where + " and a."+codetype+" = '"+ pcode+"'";
        }

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        String username= user.getUsername();

        String sql="select * from user where username = '"+user.getUsername()+"'";

        com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sql);

        if (!(theuser.getCollege() == null)){
            where = where + " and a.college = '"+ theuser.getCollege()+"'";
        }


        if (theuser.getRolevalue().equals("Department")){

            String sql1 = "SELECT a.id, a.username,a.realName,a.roleName,a.status,c.name AS college,d.name AS profession,e.name AS tclass,b.email,b.phone,b.remarks " +
                    "FROM USER a " +
                    "LEFT JOIN userinfo b ON a.id = b.userid " +
                    "LEFT JOIN organization c ON c.code = a.college " +
                    "LEFT JOIN organization d ON d.code = a.profession " +
                    "LEFT JOIN organization e ON e.code = a.tclass " +
                    "WHERE a.rolevalue != 'Super' "+where+" and a.username != '"+username+"'";

            List<usertable> ut = usertablemapper.getusertable(sql1);
            System.out.println(ut);

            Map<String, Object> result5 = new HashMap<String,Object>();
            result5.put("code",0);
            result5.put("result",ut);
            result5.put("message","提交成功!");
            result5.put("type","success");

            JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
            System.out.println(result8);

            return result8;
        }else {
            String sql1 = "SELECT a.id, a.username,a.realName,a.roleName,a.status,c.name AS college,d.name AS profession,e.name AS tclass,b.email,b.phone,b.remarks " +
                    "FROM USER a " +
                    "LEFT JOIN userinfo b ON a.id = b.userid " +
                    "LEFT JOIN organization c ON c.code = a.college " +
                    "LEFT JOIN organization d ON d.code = a.profession " +
                    "LEFT JOIN organization e ON e.code = a.tclass " +
                    "where a.username != '"+username+"' "+where+"";

            List<usertable> ut = usertablemapper.getusertable(sql1);
            System.out.println(ut);

            Map<String, Object> result5 = new HashMap<String,Object>();
            result5.put("code",0);
            result5.put("result",ut);
            result5.put("message","提交成功!");
            result5.put("type","success");

            JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
            System.out.println(result8);

            return result8;
        }


    }

    @ResponseBody
    @RequestMapping("/accountExist")
    public JSON accountExist(@RequestBody Map<String,String> params,HttpServletRequest request){
        System.out.println(params);

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        String username= params.get("account");

        String sql="select * from user where username = '"+username+"'";

        com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sql);
        System.out.println("user:"+theuser);

        Map<String, Object> result5 = new HashMap<String,Object>();

        if (theuser == null){
            result5.put("code",0);
            result5.put("result",true);
            result5.put("message","提交成功!");
            result5.put("type","success");
        }else {
            result5.put("code",-1);
            result5.put("result",false);
            result5.put("message","用户名已存在!");
            result5.put("type","error");

        }

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }



@Autowired
orgparammapper orgparammapper;
    @Autowired
    orgparamentity orgparamentity;

    @ResponseBody
    @RequestMapping("/createandedituser")
    public JSON createandedituser(@RequestBody Usertableparams params,HttpServletRequest request){
        System.out.println("接收参数："+params);

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        String username= user.getUsername();

        String sql0 = "SELECT * FROM organization a "+
                "LEFT JOIN organization b ON b.code = a.code " +
                "LEFT JOIN organization c ON c.code = a.code " ;
        String where = "";
        if (!(params.getCollege() == null)){
            where = where + " where a.name = '"+ params.getCollege()+"'";
        }
        if (!(params.getProfession() == null)){
            where = where + " or b.name = '"+ params.getProfession()+"'";
        }
        if (!(params.getTclass() == null)){
            where = where + " or c.name = '"+ params.getTclass()+"'";
        }
        System.out.println(sql0+where);

        List<organization> ut = organizationmapper.getorganization(sql0+where);
        System.out.println(ut);
        orgparamentity orgparam = new orgparamentity();
        for (organization aa: ut
             ) {
            if (aa.getType().equals("college")){
                orgparam.setCollege(aa.getCode());
            }else if (aa.getType().equals("profession")){
                orgparam.setProfession(aa.getCode());
            }else if (aa.getType().equals("tclass")){
                orgparam.setTclass(aa.getCode());

            }
        }

        if (params.getIsUpdate().equals("true")){

            String sql1 = "update userinfo set " +
                    "realname='"+params.getRealName()+"'," +
                    "phone='"+params.getPhone()+"'," +
                    //"avatar='"+params.getAvatar()+"'," +
                    "email='"+params.getEmail()+"'," +
                    "remarks='"+params.getRemarks()+ "' WHERE userid  = "+params.getId();
            System.out.println(sql1);
            int theaccount1= accountinfomapper.updateaccount(sql1);

            String sql2 = "update user set " +
                    "realName='"+params.getRealName()+"'," +
                    "college='"+   orgparam.getCollege()   +"'," +
                    "profession='"+orgparam.getProfession()+"'," +
                    "tclass='"+    orgparam.getTclass()    +"'," +
                    "awards.`user`.`desc`='"+params.getRemarks()+ "' WHERE id = "+params.getId()+"";
            System.out.println(sql2);

            int theaccount2= accountinfomapper.updateaccount(sql2);


        }else {
            String rolevalue = "";
            String token = "";
            String password = "123456";
            if (params.getRoleName().equals("student")){
                rolevalue = "student";
                token = "student";
            }else if (params.getRoleName().equals("Department")){
                rolevalue = "Department";
                token = "Department";
            }else {
                rolevalue = "Super";
                token = "super";
            }

            String sql2 = "insert into user(username,`password`,realName,roleName,rolevalue,token,`desc`,avatar,homePath,status,noticeid,email,phone,remarks,college,profession,tclass) VALUES(" +
                    "'"+params.getUsername()+"'," +
                    "'"+password+"'," +
                    "'"+params.getRealName()+"'," +
                    "'"+params.getRoleName()+"'," +
                    "'"+rolevalue+"'," +
                    "'"+token+"'," +
                    "'"+params.getRemarks()+"'," +
                    "'avatar2022-10-23-22-20-32-744.jpg'," +
                    "'/dashboard/workbench',0,'notice123'," +
                    "'"+params.getEmail()+"'," +
                    "'"+params.getPhone()+"'," +
                    "'"+params.getRemarks()+ "'," +
                    "'"+orgparam.getCollege()   +"'," +
                    "'"+orgparam.getProfession()+"'," +
                    "'"+orgparam.getTclass()    + "'" +
                    ")";
            System.out.println(sql2);
            int theaccount1= accountinfomapper.insertaccount(sql2);

            String sql3="select id from user where username = '"+params.getUsername()+"'";
            int userid=accountinfomapper.getuserid(sql3);

            String sql1 = "INSERT INTO userinfo (realname,phone,email,remarks,userid,avatar) VALUES(" +
                    "'"+params.getUsername()+"'," +
                    "'"+params.getPhone()+"'," +
                    "'"+params.getEmail()+"'," +
                    "'"+params.getRemarks()+ "'," +
                    +userid+",'avatar2022-10-23-22-20-32-744.jpg')";
            System.out.println(sql1);
            int theaccount2= accountinfomapper.insertaccount(sql1);

            String sql4 = "INSERT INTO fakecode (userid,code) values("+userid+",'2000')";
            int theaccount3= accountinfomapper.insertaccount(sql4);

        }

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",true);
        result5.put("message","提交成功!");
        result5.put("type","success");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }



@Autowired
com.example.demo.entity.userstatusparam userstatusparam;

    @Autowired
    com.example.demo.datasource.multi.dao.updatemapper updatemapper;

    @ResponseBody
    @RequestMapping("/setRoleStatus")
    public JSON setRoleStatus(@RequestBody userstatusparam params){
        System.out.println(params);

        String sql = "update user set status = '"+params.getStatus()+"' where id = "+params.getId();
        System.out.println(sql);
        int rel = updatemapper.update(sql);
        System.out.println(rel);

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",true);
        result5.put("message","提交成功!");
        result5.put("type","success");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }

    @Autowired
    Deletemapper deletemapper;

    @ResponseBody
    @RequestMapping("/deleteuser")
    public JSON deleteuser(@RequestBody Map<String,String> params){
        System.out.println(params);
        String id=params.get("userid");

        String sql = "delete from user where id = "+id;
        System.out.println(sql);
        int rel = deletemapper.delete(sql);
        System.out.println(rel);

        String sql1 = "delete from userinfo where userid = "+id;
        System.out.println(sql);
        int rel1 = deletemapper.delete(sql1);
        System.out.println(rel1);

        String sql2 = "delete from fakecode where userid = "+id;
        System.out.println(sql2);
        int rel2 = deletemapper.delete(sql2);
        System.out.println(rel2);

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",true);
        result5.put("message","提交成功!");
        result5.put("type","success");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }
    @Autowired
    com.example.demo.util.getip getip;
    /**
     * 端口
     */
    @Value("${server.port}")
    private String port;
    @Autowired
    com.example.demo.datasource.multi.dao.dynamicinfomapper dynamicinfomapper;

    @RequestMapping("/getdynamicinfo")
    @ResponseBody
    public JSON getdynamicinfo(HttpServletRequest request){

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        String username= user.getUsername();

        String sql0="select * from user where username = '"+user.getUsername()+"'";

        com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sql0);

        String sql = "select a.handleaction,a.handletime,`handler`,b.applicationawards,c.username,c.avatar from workflow a  " +
                "LEFT JOIN application b ON b.pkid = a.pkid " +
                "LEFT JOIN `user` c on  c.id = b.userid where c.college = '"+theuser.getCollege()+"' ORDER BY a.handletime DESC LIMIT 10";

        List<dynamicinfo> rel = dynamicinfomapper.getdynamicinfo(sql);
        System.out.println(rel);
        List<retdynamicinfo> rel1= new ArrayList<>();
        String ip = getip.getip(request);
        for (dynamicinfo dy:rel
             ) {
            retdynamicinfo rel2= new retdynamicinfo();
            rel2.setName(dy.getUsername());
            //头像url
            String newfilename = "http://" + ip + ":" + port + "/files/"+dy.getAvatar();
            rel2.setAvatar(newfilename);
            String desc = "申请的<a>"+dy.getApplicationawards()+"</a>由<a>"+dy.getHandler()+dy.getHandleaction()+"</a>";
            rel2.setDesc(desc);
            rel2.setDate(dy.getHandletime());
            System.out.println(rel2);
            rel1.add(rel2);
        }

        System.out.println(rel1);
        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",rel1);
        result5.put("message","提交成功!");
        result5.put("type","success");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }

    @Autowired
    com.example.demo.datasource.multi.dao.noticemapper noticemapper;

    @RequestMapping("/getnoticeinfo")
    @ResponseBody
    public JSON getnoticeinfo(HttpServletRequest request){

        String sql1="SELECT a.*, b.avatar FROM `notice` a LEFT JOIN `user` b ON b.username = a.creater LEFT JOIN userinfo c on c.userid = b.id where dr = 0 ORDER BY a.createtime desc LIMIT 5";
        System.out.println(sql1);

        List<notice2> thenoticelist=noticemapper.getnoticelist2(sql1);
        String ip = getip.getip(request);
        for (notice2 no:thenoticelist
        ) {

            //头像url
            String newfilename = "http://" + ip + ":" + port + "/files/"+no.getAvatar();
            no.setAvatar(newfilename);

            String undecodejs = StringEscapeUtils.unescapeEcmaScript(no.getContent());

            String undecodejava= StringEscapeUtils.unescapeJava(undecodejs);
            no.setContent(undecodejava);
        }

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",thenoticelist);
        result5.put("message","提交成功!");
        result5.put("type","success");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));


        return result8;
    }

    @Autowired
    organizationmapper organizationmapper;
    @Autowired
    com.example.demo.entity.organizationre organizationre;

    @RequestMapping("/getorganization")
    @ResponseBody
    public JSON getorganization(HttpServletRequest request){

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        String username= user.getUsername();

        String sql="select * from user where username = '"+user.getUsername()+"'";

        com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sql);

        String sql1;
        if (theuser.getRolevalue().equals("Department")){

             sql1 = "SELECT * FROM organization WHERE code = '"+theuser.getCollege()+"' OR  " +
                    "father = '"+theuser.getCollege()+"' " +
                    "OR `father` in (SELECT code FROM organization WHERE type != 'college' AND  father = '"+theuser.getCollege()+"')";
        }else {
             sql1 = "SELECT * FROM organization";

        }

        List<organization> ut = organizationmapper.getorganization(sql1);
        System.out.println(ut);

        List<organizationre> orglist = new ArrayList<>();
        for (organization aa:ut
        ) {
            organizationre college = new organizationre();
            if (aa.getType().equals("college")){
                college.setCode(aa.getCode());
                college.setId(aa.getCode());
                college.setName(aa.getName());
                college.setType(aa.getType());
                List<organizationre> professionlist = new ArrayList<>();
                for (organization bb:ut
                ) {
                    organizationre profession = new organizationre();
                    if (bb.getType().equals("profession") && aa.getCode().equals(bb.getFather())){
                        profession.setCode(bb.getCode());
                        profession.setId(bb.getCode());
                        profession.setName(bb.getName());
                        profession.setType(bb.getType());

                        //再加个for遍历班级
                        List<organizationre> tclasslist = new ArrayList<>();
                        for (organization cc:ut
                        ) {
                            organizationre tclass = new organizationre();
                            if (cc.getType().equals("tclass") && bb.getCode().equals(cc.getFather())){

                                tclass.setCode(cc.getCode());
                                tclass.setId( cc.getCode());
                                tclass.setName(cc.getName());
                                tclass.setType(cc.getType());
                                tclass.setChildren(null);

                                tclasslist.add(tclass);
                            }

                        }
                        profession.setChildren(tclasslist);
                        professionlist.add(profession);
                    }
                }

                college.setChildren(professionlist);
                orglist.add(college);

            }
        }

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",orglist);
        result5.put("message","提交成功!");
        result5.put("type","success");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }

}
